import axios from 'axios';
import { message } from 'antd';
// 是否使用接口地址
const useInterface = true;

const successCode = 200;
const errorCode = [401, 201, 403, 404];
const redirectCode = [302, 405, 500, '500'];
const codeString = 'status';
const baseUrl = process.env.baseUrl;

const baseService = axios.create({
  baseURL: baseUrl,
  withCredentials: false,
  timeout: 5 * 60 * 1000,
});

// request interceptors
baseService.interceptors.request.use(
  (config) => {
    const token = window.sessionStorage.getItem('APP_TOKEN');
    if (token) {
      config.headers = {
        'X-Access-Token': token,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// response interceptors
baseService.interceptors.response.use(
  (response) => {
    // 判断接口状态
    const status_code = response[codeString];
    if (status_code === successCode) {
      // 判断data.code
      if (redirectCode.includes(response.data.code)) {
        // 非successCode
        message.error('Server Error');
        return Promise.reject('Server Error');
      }
      return response.data;
    } else if (errorCode.includes(status_code)) {
      // 失败
      // special code
      return Promise.reject('登录状态错误');
    } else if (redirectCode.includes(status_code)) {
      // 重定向
      message.error('登录状态错误');
      return Promise.reject('Server Error');
    } else {
      // 其他
      message.error('Server Error');
      // other code
      return Promise.reject('Server Error');
    }
  },
  (error) => {
    return Promise.reject(error);
  },
);

export { baseService, baseUrl, useInterface };
